package com.music.activity;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.content.FileProvider;
import android.util.Log;

import com.music.utilbean.KuwoApplication;
import com.music.utilbean.MediaUtils;
import com.music.utilbean.Mp3Info;

import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * 音乐播放的服务类
 * 功能：
 * 1、播放
 * 2、暂停
 * 3、上一首
 * 4、下一首
 * 5、获取当前播放进度
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener, OnErrorListener {
	public MediaPlayer mediaPlayer;
	public static final String TAG = "PlayService";
	private ArrayList<Mp3Info> mp3Infos;
	private MusicUpdateListener musicUpdateListener;
	private ExecutorService es      = Executors.newSingleThreadExecutor();
	private boolean         ispause = false;
	private int currentPosition;//当前正在播放的位置
	private             int play_mode   = ORDER_PLAY;//播放模式，顺序，随机，单曲循环
	public static final int ORDER_PLAY  = 1;
	public static final int RANDOM_PLAY = 2;
	public static final int SINGLE_PLAY = 3;

	public void setPlay_mode(int play_mode) {
		this.play_mode = play_mode;
	}

	public int getPlay_mode() {
		return play_mode;
	}

	class PlayBinder extends Binder {
		public PlayService getPlayService() {
			return PlayService.this;
		}
	}

	public PlayService() {
	}

	@Override
	public void onCreate() {
		super.onCreate();
		KuwoApplication application = (KuwoApplication) getApplication();
		currentPosition = application.sharedPreferences.getInt("currentposition", 0);
		play_mode = application.sharedPreferences.getInt("play_mode", PlayService.ORDER_PLAY);
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mp3Infos = MediaUtils.getMp3Infos(this);//MeidaUtil得到系统所有音乐的处理类
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		Log.i("ServiceCreated", "mp3infos的大小:" + mp3Infos.size());
		es.execute(updateStatusRunnable);//开启线程
	}

	public void onDestroy() {//结束线程
		super.onDestroy();
		if (es != null && !es.isShutdown()) {
			es.shutdown();
			es = null;
		}
	}


	Runnable updateStatusRunnable = new Runnable() {
		@Override
		public void run() {
			while (true) {
				if (musicUpdateListener != null && mediaPlayer != null && mediaPlayer.isPlaying()) {
					musicUpdateListener.onPublish(getCurrentProgress());
				}
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};

	/////////////////////////////////////////////////////////////////////////////
	//播放
	public void play(int position) {
		if (position >= 0 && position < mp3Infos.size()) {
			Mp3Info mp3Info = mp3Infos.get(position);
			Log.e(TAG, "play: " + mp3Info.getTitle());
			mediaPlayer.reset();
			try {
				if (Build.VERSION.SDK_INT > 23) {
					//如果是安卓7.0及其以上的手机就通过FileProvider来获取mp3文件。否则容易出现mediaplayer的-38错误。
					Uri uriForFile = FileProvider.getUriForFile(this, "com.music.fileProvider", new File(mp3Info.getUrl()));
					mediaPlayer.setDataSource(this, uriForFile);
				} else {
					mediaPlayer.setDataSource(this, Uri.parse(mp3Info.getUrl()));
				}
				mediaPlayer.prepare();
				mediaPlayer.start();
				currentPosition = position;
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (musicUpdateListener != null) {
				musicUpdateListener.onChange(currentPosition);
			}

		}
	}

	//暂停
	public void pause() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
			ispause = true;
		}
	}

	//下一首
	public void next() {
		if (currentPosition >= mp3Infos.size() - 1) {
			currentPosition = 0;
		} else {
			currentPosition++;
		}
		play(currentPosition);
	}

	//上一首
	public void prev() {
		if (currentPosition - 1 < 0) {
			currentPosition = mp3Infos.size() - 1;
		} else {
			currentPosition--;
		}
		play(currentPosition);
	}

	public void start() {
		if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
			mediaPlayer.start();

		}
	}
	/////////////////////////////////////////////////////////////

	// 获取音乐长度
	public int getDuration() {
		return mediaPlayer.getDuration();
	}

	//获取当前播放的歌曲的进度
	public int getCurrentProgress() {
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			return mediaPlayer.getCurrentPosition();
		}
		return 0;
	}

	//获取当前歌曲进度条
	public int getcurrentpositions() {
		return mediaPlayer.getCurrentPosition();
	}

	//获取当前播放的歌曲的position
	public int getCurrentPosition() {
		return currentPosition;
	}

	public void seekTo(int msec) {
		mediaPlayer.seekTo(msec);

	}

	//更新状态的接口
	public interface MusicUpdateListener {
		public void onPublish(int progress);//更新进度条
		public void onChange(int position);//歌曲改变时
	}

	public MusicUpdateListener getMusicUpdateListener() {
		return musicUpdateListener;
	}

	public void setMusicUpdateListener(MusicUpdateListener musicUpdateListener) {
		this.musicUpdateListener = musicUpdateListener;
	}

	@Override
	public IBinder onBind(Intent intent) {//第一步执行onbind方法
		IBinder result = null;
		if (null == result) {
			result = new PlayBinder();
		}
		return result;
	}

	public boolean isplaying() {
		if (mediaPlayer != null) {
			return mediaPlayer.isPlaying();
		}
		return false;
	}

	public boolean ispause() {
		return ispause;
	}

	private Random random = new Random();

	@Override
	public void onCompletion(MediaPlayer arg0) {
		switch (play_mode) {
			case ORDER_PLAY:
				next();
				break;
			case RANDOM_PLAY:
				play(random.nextInt(mp3Infos.size()));
				break;
			case SINGLE_PLAY:
				play(currentPosition);
				break;
		}

	}

	@Override
	public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
		mediaPlayer.reset();
		Log.e(TAG, "onError: "+what );
		return false;
	}
}
